<?php

namespace p5\objects;

/**
 * Created by PhpStorm.
 * User: simon
 * Date: 2015/11/23
 * Time: 9:43
 */
class RequestUtils
{

    public static function trim_arg($url)
    {
        $urls = explode("?", $url);
        return $urls[0];
    }


    public static function first($names)
    {
        if (is_string($names)) {
            $names = explode(",", $names);
        }
        foreach ($names as $name) {
            $value = self::get($name);
            if (!empty($value)) {
                return $value;
            }
        }
        return "";
    }

    public static function get($argName, $defaultValue = "", $replaceQuota = false)
    {
        $temp = self::get_parameter($argName, $defaultValue);
        if ($replaceQuota) {
            $temp = str_replace("'", "''", $temp);
        }
        return $temp;
    }

    public static function get_int($argName, $defaultValue = -1)
    {
        $value = self::get($argName, false, $defaultValue);
        if (is_array($value)) {
            return $defaultValue;
        }
        return ValidateUtils::isInt($value) ? $value : $defaultValue;
    }

    public static function get_parameter($argName, $default = "")
    {
        $matrix = self::get_parameters();
        if (array_key_exists($argName, $matrix)) {
            return $matrix[$argName];
        }
        return $default;
    }

    public static function get_parameters($names = array(), $filter_empty_value = true)
    {
        $matrix = $_REQUEST;
        if (!isset($matrix) || !is_array($matrix)) {
            if ($_SERVER["REQUEST_METHOD"] == "POST") {
                $matrix = $_POST;
            } else if ($_SERVER["REQUEST_METHOD"] == "GET") {
                $matrix = $_GET;
            }
        }
        $keys = array_keys($matrix);
        if (!empty($keys) && count($keys) > 0) {
            if (strpos($keys[0], "Content-Disposition:_form-data") > 0) {
                /** 以 form-data 的方式解析参数
                 * $_POST['------WebKitFormBoundaryiGa3Zi35s3MTFUsq Content-Disposition:_form-data;_name']
                 * "the_date" 2019-10-07
                 * ------WebKitFormBoundaryiGa3Zi35s3MTFUsq Content-Disposition: form-data; name="filterId"
                 * ------WebKitFormBoundaryiGa3Zi35s3MTFUsq Content-Disposition: form-data; name="method" POST
                 * ------WebKitFormBoundaryiGa3Zi35s3MTFUsq Content-Disposition: form-data; name="uri" scheduleWx/getWeekSchedulesByDate
                 * ------WebKitFormBoundaryiGa3Zi35s3MTFUsq--
                 */
                $matrix = static::parseFormData($matrix[$keys[0]]);
            }
        }
        if (empty($names)) {
            $names = array_keys($matrix);
        } else if (!is_array($names)) {
            $names = explode(",", $names);
        }

        $result = array();
        for ($i = 0; $i < count($names); $i++) {
            $name = $names[$i];
            if (array_key_exists($name, $matrix)) {
                if ($filter_empty_value == true && $matrix[$name] == "") {
                    continue;
                }
                $result[$name] = $matrix[$name];
            }
        }
        return $result;
    }


    public static function parseFormData($data)
    {
        $array = [];
        $params = explode("------", "Content-Disposition: form-data; name=" . $data);
        foreach ($params as $param) {
            $key = "";
            $list = explode("\r\n", $param);
            $isSkipRow = false;
            foreach ($list as $value) {
                if ($isSkipRow) {
                    $isSkipRow = false;
                    continue;
                }
                if (strstr($value, 'WebKitFormBoundary')) continue;
                if (strpos($value, 'form-data; name=')) {
                    $key = str_replace('"', '', strchr($value, '"'));
                    $isSkipRow = true;
                    continue;
                };
                if (!empty($key)) {
                    $array[$key] = $value;
                }
                break;
            }
        }
        return $array;
    }


    public static function get_website_url()
    {
        global $_SERVER;

        $matrix = explode("/", $_SERVER["SERVER_PROTOCOL"]);

        $url = $matrix[0] . "://";
        $url = $url . $_SERVER["SERVER_NAME"];
        $url = $url . (($_SERVER["SERVER_PORT"] == 80) ? "" : (":" . $_SERVER["SERVER_PORT"]));
        $url = $url . "/";
        return strtolower($url);
    }

    public static function get_ahead_path($path, $n)
    {
        $chr = "/";
        $paths = explode($chr, $path);
        $base = $paths[0];
        for ($i = 1; $i < (count($paths) - $n); $i++) {
            $base .= $chr . $paths[$i];
        }
        return $base;
    }


    public static function get_remote_addr()
    {
        global $_SERVER;
        $headers = apache_request_headers();
        $key = "X-Forwarded-For";
        if (array_key_exists($key, $headers) && $headers[$key] != "") {
            $string = $headers[$key];
            $matrix = explode(",", $string);
            return $matrix[0];
        }
        return $_SERVER["REMOTE_ADDR"];
    }

    public static function _get_browser()
    {
        $browser = array( //reversed array
            "OPERA",
            "MSIE",            // parent
            "CHROME",
            "NETSCAPE",
            "FIREFOX",
            "KONQUEROR",
            "MOZILLA",        // parent
            "SAFARI"
        );
        $info["browser"] = "OTHER";
        foreach ($browser as $parent) {
            if (($s = strpos(strtoupper($_SERVER['HTTP_USER_AGENT']), $parent)) !== FALSE) {
                $f = $s + strlen($parent);
                $version = substr($_SERVER['HTTP_USER_AGENT'], $f, 5);
                $version = preg_replace('/[^0-9,.]/', '', $version);

                $info["browser"] = $parent;
                $info["version"] = $version;
                break;
            }
        }
        return $info;
    }


    public static function get_client_browser()
    {
        // Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; BRI/2; .NET4.0C)
        // Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0
        // Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11

        $browser = get_browser(null, true);
        return $browser["browser"];
    }


    public static function is_ie()
    {
        $browser = self::_get_browser();
        return ($browser["browser"] == "MSIE");
    }

    public static function is_firefox()
    {
        $browser = self::_get_browser();
        return ($browser["browser"] == "FIREFOX");
    }

    public static function is_chrome()
    {
        $browser = self::_get_browser();
        return ($browser["browser"] == "CHROME");
    }

    public static function is_ie7()
    {
        $browser = self::_get_browser();
        return ($browser["browser"] == "MSIE" && $browser["version"] * 1 > 6 && $browser["version"] * 1 < 8);
    }

    public static function is_ie8()
    {
        $browser = self::_get_browser();
        return ($browser["browser"] == "MSIE" && $browser["version"] * 1 > 7 && $browser["version"] * 1 < 9);
    }

    public static function is_ie9()
    {
        $browser = self::_get_browser();
        return ($browser["browser"] == "MSIE" && $browser["version"] * 1 > 8 && $browser["version"] * 1 < 10);
    }

    public static function note_back_url($flag = "")
    {
        global $_SERVER;
        $matrix = explode("#", $_SERVER["REQUEST_URI"]);
        $url = $matrix[0];
        SessionUtils::set_session("_BACK_URL" . $flag, $url);
    }

    public static function load_back_url($flag = "")
    {
        return SessionUtils::get_session("_BACK_URL" . $flag);
    }

    static public function buildLink($url, $args = [])
    {
        $string = self::linkArgs($args);
        if (empty($string)) {
            return $url;
        }
        if (strpos($url, "?") === false) {
            return $url . "?" . $string;
        }
        return $url . "&" . $string;
    }

    static public function linkArgs($args)
    {
        $matrix = [];
        foreach ($args as $name => $value) {
            $string = $name . "=" . urlencode($value);
            array_push($matrix, $string);
        }
        return implode("&", $matrix);
    }

    static public function linkedArgsToMap($string)
    {
        if (empty($string)) {
            return [];
        }
        $index = strpos($string, "?");
        if ($index !== false && $index > 0) {
            $string = substr($string, $index + 1);
        }
        $result = [];
        $matrix = explode("&", $string);
        foreach ($matrix as $item) {
            $temp = explode("=", $item);
            if (count($temp) == 1) {
                $result[$temp[0]] = "";
            } else {
                $result[$temp[0]] = $temp[1];
            }
        }
        return $result;
    }

    static public function getUrlQueryString()
    {
        global $_SERVER;
        if (array_key_exists("QUERY_STRING", $_SERVER)) {
            return $_SERVER["QUERY_STRING"];
        }
        if (array_key_exists("REDIRECT_QUERY_STRING", $_SERVER)) {
            return $_SERVER["REDIRECT_QUERY_STRING"];
        }
        return static::trim_arg($_SERVER["REQUEST_URI"]);
    }

    static public function headers()
    {
        $result = [];
        $list = headers_list();
        foreach ($list as $item) {
            $index = strpos($item, ":");
            if ($index === false) {
                array_push($result, $item);
                continue;
            }
            $key = substr($item, 0, $index);
            $value = substr($item, $index + 1);
            $result[trim($key)] = trim($value);
        }
        return $result;
    }

    static public function getHeader($name)
    {
        $headers = static::headers();
        if (array_key_exists($name, $headers)) {
            return $headers[$name];
        }
        return "";
    }
}
